import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from '../../entities/product.entity';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { QueryProductDto } from './dto/query-product.dto';
import { BusinessException } from 'src/common/exceptions/business.exception';
import { ErrorCode } from 'src/common/constants/error-code.enum';

/**
 * 商品服务
 */
@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  /**
   * 创建商品
   */
  async create(createProductDto: CreateProductDto) {
    const product = this.productRepository.create(createProductDto);
    return await this.productRepository.save(product);
  }

  /**
   * 查询商品列表（分页）
   */
  async findAll(queryDto: QueryProductDto) {
    const { page = 1, limit = 10, keyword, categoryId } = queryDto;

    const queryBuilder = this.productRepository.createQueryBuilder('product');

    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere('product.title LIKE :keyword', {
        keyword: `%${keyword}%`,
      });
    }

    // 分类筛选
    if (categoryId) {
      queryBuilder.andWhere('product.categoryId = :categoryId', {
        categoryId,
      });
    }

    // 分页
    const total = await queryBuilder.getCount();
    const products = await queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('product.createdAt', 'DESC')
      .getMany();

    return {
      data: products,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 根据ID查询商品
   */
  async findOne(id: string) {
    const product = await this.productRepository.findOne({
      where: { id },
    });

    if (!product) {
      throw new BusinessException(ErrorCode.PRODUCT_NOT_FOUND);
    }

    return product;
  }

  /**
   * 更新商品
   */
  async update(id: string, updateProductDto: UpdateProductDto) {
    const product = await this.findOne(id);
    Object.assign(product, updateProductDto);
    return await this.productRepository.save(product);
  }

  /**
   * 删除商品（软删除）
   */
  async remove(id: string) {
    const product = await this.findOne(id);
    await this.productRepository.softRemove(product);
    return { message: '删除成功' };
  }

  /**
   * 获取热门商品
   */
  async getHotProducts(limit: number = 10) {
    return await this.productRepository.find({
      where: { isHot: true, status: 'published' },
      order: { views: 'DESC', createdAt: 'DESC' },
      take: limit,
    });
  }

  /**
   * 获取推荐商品
   */
  async getFeaturedProducts(limit: number = 10) {
    return await this.productRepository.find({
      where: { isFeatured: true, status: 'published' },
      order: { sort: 'DESC', createdAt: 'DESC' },
      take: limit,
    });
  }

  /**
   * 增加浏览量
   */
  async incrementViews(id: string) {
    await this.productRepository.increment({ id }, 'views', 1);
  }

  /**
   * 增加下载量
   */
  async incrementDownloads(id: string) {
    await this.productRepository.increment({ id }, 'downloads', 1);
  }

  /**
   * 发布商品
   */
  async publish(id: string) {
    const product = await this.findOne(id);
    product.status = 'published';
    return await this.productRepository.save(product);
  }

  /**
   * 下架商品
   */
  async offline(id: string) {
    const product = await this.findOne(id);
    product.status = 'offline';
    return await this.productRepository.save(product);
  }
}
